package com.qiall.bashutil;


import java.io.BufferedReader;
import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;

import ch.ethz.ssh2.Connection;
import ch.ethz.ssh2.SCPClient;
import ch.ethz.ssh2.SFTPException;
import ch.ethz.ssh2.SFTPv3Client;
import ch.ethz.ssh2.Session;
import ch.ethz.ssh2.StreamGobbler;
import org.apache.commons.lang3.StringUtils;


public class ScpExecUtil {




    /**
     * 远程文件传输，如果local参数是文件，则本地传输到远程；如果是目录，则远程传输到本地
     *
     * @param remoteIp
     *            远程主机IP或hostname
     * @param user
     *            远程主机用户名
     * @param password
     *            远程主机对应密码
     * @param local
     *            本地主机文件名（本地->远程）；本地主机目录名（远程->本地）
     * @param remote
     *            远程主机目录名（本地->远程）；远程主机文件名（远程->本地）
     * @return 返回true：成功。false：失败
     */
    public static boolean scpFile(String remoteIp, String user,
                                  String password, String local, String remote) {
        Connection con = new Connection(remoteIp);
        try {
            con.connect();
            boolean isAuthed = con.authenticateWithPassword(user, password);

            if (!isAuthed) {
                //logger.error("远程主机" + remoteIp + "用户名或密码验证失败！");
                return false;
            }

            SCPClient scpClient = con.createSCPClient();
            File localFile = new File(local);
            if (localFile.isFile()) {
                if (!localFile.exists()) {
                    //logger.error("本地文件" + local + "不存在，无法传输！");
                    return false;
                } else {
                    try {
                        SFTPv3Client sftpClient = new SFTPv3Client(con);
                        // 远程新建目录
                        sftpClient.mkdir(remote, 0777);
                    } catch (SFTPException e1) {
                        //	logger.info("目录" + remote + "已存在，无需再创建。");
                    }

                    try {
                        scpClient.put(local, remote, "0777");
                    } catch (IOException e2) {
                        //logger.error("路径" + remote + "不是一个文件夹。");
                        return true;
                    }

                    // 上传到远程主机上的文件
                    String filename = local
                            .substring(local.lastIndexOf('/') + 1);
                    Session session = con.openSession();
                    session.execCommand("ls -l " + remote + "/" + filename);
                    InputStream is = new StreamGobbler(session.getStdout());
                    BufferedReader br = new BufferedReader(
                            new InputStreamReader(is));
                    String line = br.readLine();
                    br.close();
                    is.close();
                    session.close();
                    if (!StringUtils.isEmpty(line)) {
                        return true;
                    }
                }
            } else {
                if (!localFile.exists()) {
                    localFile.mkdirs();
                }

                scpClient.get(remote, local);

                String filename = remote.substring(remote.lastIndexOf('/') + 1);
                if (new File(local + "/" + filename).exists()) {
                    return true;
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        }

        con.close();
        return false;
    }

    public static void main(String[] args) {
        scpFile("app.aixinfang.vip","root","aixinfangRoot@PassW0rd$","C:\\Users\\Administrator\\Documents\\WeChat Files\\wxid_r07zfia49q3422\\FileStorage\\MsgAttach\\9e20f478899dc29eb19741386f9343c8\\File\\2022-07\\axf\\target\\management-platform-0.0.1-SNAPSHOT.jar","/root/manage_platform/");
    }
}